package com.github.thinwonton.springboot.showcase.poi.apache;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class ImportExcel {
    private static final String excelFilePath = "file/demo.xlsx";

    public static void main(String[] args) throws IOException, InvalidFormatException {
        File file = classpathFile(excelFilePath);

        //创建对象
        Workbook workbook = new XSSFWorkbook(file);

        //获取sheet数量
        int numberOfSheets = workbook.getNumberOfSheets();
        System.out.println("sheet number is " + numberOfSheets);

        //获取第三个sheet
        Sheet sheet2 = workbook.getSheetAt(2);

        //遍历输出sheet
        int physicalNumberOfRows = sheet2.getPhysicalNumberOfRows();
        for (int i = 0; i < physicalNumberOfRows; i++) {
            Row row = sheet2.getRow(i);
            Cell cell = row.getCell(0);
            if (i == 0) {
                //标题行
                System.out.println("标题：" + cell.getStringCellValue());
            } else {
                System.out.println("值：" + cell.getStringCellValue());
            }

        }
    }

    private static File classpathFile(String path) {
        URL systemResource = ClassLoader.getSystemResource(path);
        return new File(systemResource.getFile());
    }

}
